<?php
/**
 * Created by PhpStorm.
 * User: MSQ
 * Date: 2021/9/24
 * Time: 14:27
 */

namespace App\Utils;


use EasySwoole\EasySwoole\Config;

class FileUtil
{
    /**
     * 将amr转成mp3
     * @param string $amrfilePath amr文件路径
     */
    public static function converterDecoderMp3(string $amrfilePath): void
    {
        $uploadConfig = Config::getInstance()->getConf("UPLOAD");
        $coderFilePath = $uploadConfig['silkv3_file_path'] ?? '';
        if ($coderFilePath) {
            $decoderCmd = $coderFilePath . " " . $amrfilePath;
            $res = exec($decoderCmd, $allRes);
//            var_dump($allRes);
            $data = substr($res, -7, -1);
            if ($data !== 'Finish') {
                LogHelp::error("转换错误，错误原因：{$res}", 'socket');
            }
        } else {
            LogHelp::error('转换文件配置不存在', 'socket');
        }
	}

    public static function saveFile(\EasySwoole\Http\Message\UploadFile $file): array
    {
        $uploadConfig = Config::getInstance()->getConf("UPLOAD");
        $date = date('Ymd');
        // 文件格式
        $index = strrpos($file->getClientFilename(), '.');
        $suffix = substr($file->getClientFilename(), $index+1);
        // 新文件名
        $time = time();
        $md5 = strtoupper(md5($time.$file->getSize()));

        // 转移文件
        $newPath = "{$uploadConfig['local_path']}{$uploadConfig['file_path']}/{$date}/{$md5}.{$suffix}";
//        $newCompressPath = "{$uploadConfig['local_path']}{$uploadConfig['file_path']}/{$date}/{$md5}_050.{$suffix}";
        $file->moveTo($newPath);

        // 文件权限
        self::changeFilePermission($newPath);

        // 转换格式【amr转mp3】
        if (strtolower($suffix) == 'amr') {
            self::converterDecoderMp3($newPath);

            $suffix = 'mp3';
        }

        // 压缩图片
        if ($file->getSize() > 3*1024*1024 && strtolower($suffix) == 'jpg') {
            (new ImageCompressUtil($newPath, 0.7))->compressImg($newPath);
        }

        // url
        $siteConfig = Config::getInstance()->getConf("SITE");
        $url = "{$siteConfig['domain']}/juliao/{$date}/{$md5}.{$suffix}";

        // 文件权限
        self::changeFilePermission($newPath);

        return [
            'url' => $url,
            'fileSize' => $file->getSize(),
        ];
    }

    /**
     * 文件修改权限
     * @param string $filePath
     */
    public static function changeFilePermission(string $filePath): void
    {
        // 文件权限
        chmod($filePath, 0755);
        chgrp($filePath, 'www');
        chown($filePath, 'www');
    }

    /**
     * 获取文件路径
     * @param string $url
     * @return string
     */
    public static function getFileUrlPath(string $url): string
    {
        if (empty($url)) {
            return $url;
        }

        $index = strpos($url,'/juliao/');
        if ($index === false) {
            return '';
        }

        return substr($url, $index);
    }

    /**
     * 获取文件配置url
     * @param string $url
     * @return string
     */
    public static function getFileConfigUrl(string $url): string
    {
        if (empty($url)) {
            return $url;
        }

        $path = self::getFileUrlPath($url);
        if (empty($path)) {
            return $url;
        }

        // url
        $siteConfig = Config::getInstance()->getConf("SITE");

        return $siteConfig['domain'].$path;
    }
}
